package com.stark.commons.spring.web.support.zuul;

import java.util.Set;

import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.netflix.ribbon.apache.RibbonLoadBalancingHttpClient;
import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommand;
import org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFactory;

import com.stark.commons.spring.web.boot.properties.ZuulTimeoutProperties;

/**
 * 扩展 {@link org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFactory} ，
 * 使用自定义的 {@link com.stark.commons.spring.web.support.zuul.CustomHttpClientRibbonCommand} ，
 * 支持 uri 接口级别的超时配置。
 * 
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0
 * @see org.springframework.cloud.netflix.zuul.filters.route.apache.HttpClientRibbonCommandFactory
 * @see com.stark.commons.spring.web.support.zuul.CustomHttpClientRibbonCommand
 * @see com.stark.commons.spring.web.support.zuul.CustomRibbonApacheHttpRequest
 */
public class CustomHttpClientRibbonCommandFactory extends HttpClientRibbonCommandFactory {

	private final SpringClientFactory clientFactory;

	private final ZuulProperties zuulProperties;
	
	private final ZuulTimeoutProperties zuulTimeoutProperties;
	
	public CustomHttpClientRibbonCommandFactory(SpringClientFactory clientFactory, ZuulProperties zuulProperties,
			Set<FallbackProvider> zuulFallbackProviders, ZuulTimeoutProperties zuulTimeoutProperties) {
		super(clientFactory, zuulProperties, zuulFallbackProviders);
        this.clientFactory = clientFactory;
        this.zuulProperties = zuulProperties;
        this.zuulTimeoutProperties = zuulTimeoutProperties;
	}
	
	@Override
	public HttpClientRibbonCommand create(RibbonCommandContext context) {
		FallbackProvider zuulFallbackProvider = getFallbackProvider(context.getServiceId());
		final String serviceId = context.getServiceId();
		final RibbonLoadBalancingHttpClient client = clientFactory.getClient(serviceId, RibbonLoadBalancingHttpClient.class);
		client.setLoadBalancer(clientFactory.getLoadBalancer(serviceId));

		return new CustomHttpClientRibbonCommand(serviceId, client, context, zuulProperties, zuulFallbackProvider, zuulTimeoutProperties);
	}

}
